<template>
  <view class="ai-chat-component">
    <view style="display: none" module="sseConnector" ref="sseConnector" :id="sseId" :prop="sseId" :change:prop="sseConnector.onSSEIdChange"></view>
  </view>
</template>

<script>
import modelManager from '@/store/model.js'

export default {
  name: 'ai-chat',
  props: {
    modelId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      sseId: '',
      isLoading: false,
      currentMessages: [], // 当前对话的所有消息
      currentAIResponse: '' // 当前AI回复的累积内容
    }
  },
  created() {
  },
  methods: {
    // 处理SSE数据
    handleSSEData(res) {
      try {
        const delta = res.choices[0].delta;
        this.$emit('ai-message', delta);
        
        // 累积AI回复内容
        if (delta.content) {
          this.currentAIResponse += delta.content;
        }
        
        // 如果收到了结束标记，完成对话
        if (delta.finish_reason === 'stop') {
          this.finishConversation();
        }
      } catch (e) {
        if (e instanceof Error) {
          this.handleSSEError(e);
        }
      }
    },
    
    // 完成当前对话
    finishConversation() {
      if (this.currentAIResponse.trim() !== '') {
        // 创建助手消息对象
        const assistantMessage = {
          role: 'assistant',
          content: this.currentAIResponse
        };
        
        // 添加到当前消息数组
        this.currentMessages.push(assistantMessage);
        
        // 发出消息更新事件
        this.$emit('messages-updated', [...this.currentMessages]);
        
        // 重置当前AI回复
        this.currentAIResponse = '';
      }
      
      // 更新加载状态
      this.isLoading = false;
      this.$emit('loading', false);
      
      // 发出SSE关闭事件，确保总结生成逻辑能够触发
      uni.$emit('sse-closed');
    },
    
    // 处理SSE错误
    handleSSEError(err) {
      if (!this.isLoading) return;
      
      // 更新加载状态
      this.isLoading = false;
      this.$emit('loading', false);
      
      // 发出错误事件
      this.$emit('error', err);
      
      // 如果是SSE连接关闭，且有累积的AI回复内容，将其添加到消息历史
      if (err.type === 'SSE_CLOSED') {
        // 发出专门的SSE关闭事件
        uni.$emit('sse-closed');
        
        if (this.currentAIResponse.trim() !== '') {
          // 创建助手消息对象
          const assistantMessage = {
            role: 'assistant',
            content: this.currentAIResponse
          };
          
          // 添加到当前消息数组
          this.currentMessages.push(assistantMessage);
          
          // 发出消息更新事件
          this.$emit('messages-updated', [...this.currentMessages]);
          
          // 重置当前AI回复
          this.currentAIResponse = '';
        }
      }
      
      // 只在非正常关闭时显示错误提示
      if (!err.type || err.type !== 'SSE_CLOSED') {
        uni.showToast({
          title: '连接异常',
          icon: 'none'
        });
      }
    },
    
    // 发送消息
    async sendMessage(userMsg, historyMessages = [], customModelId = '') {
      if (this.isLoading) return;

      // 更新加载状态
      this.isLoading = true;
      this.$emit('loading', true);
      
      // 重置当前AI回复
      this.currentAIResponse = '';

      // 确定使用的模型ID
      const useModelId = customModelId || this.modelId || modelManager.currentModel;

      // 初始化消息历史
      this.currentMessages = historyMessages.length > 0 ? [...historyMessages] : [];
      
      // 构建消息数组
      const messages = [...this.currentMessages];
      
      // 只有当用户消息不为空时才添加
      if (userMsg && typeof userMsg === 'string' && userMsg.trim() !== '') {
        const lastMessage = this.currentMessages.length > 0 ? 
          this.currentMessages[this.currentMessages.length - 1] : null;
          
        if (!lastMessage || lastMessage.role !== 'user' || lastMessage.content !== userMsg) {
          const userMessage = { role: 'user', content: userMsg };
          messages.push(userMessage);
          this.currentMessages.push(userMessage);
        }
      }

      // 获取消息ID
      this.requestMessageId(useModelId, messages);
    },
    
    // 请求消息ID
    requestMessageId(modelId, messages) {
      uni.request({
        url: 'http://38.207.185.69:3000/aiPutParms',
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          model: modelId,
          messages: messages
        },
        success: res => {
          if (res.statusCode === 200 && res.data.id) {
            this.sseId = res.data.id;
          } else {
            this.handleRequestError('获取会话ID失败');
          }
        },
        fail: err => {
          this.handleRequestError('初始化失败', err);
        }
      });
    },
    
    // 处理请求错误
    handleRequestError(message, err = null) {
      this.isLoading = false;
      this.$emit('loading', false);
      if (err) this.$emit('error', err);
      
      uni.showToast({
        title: message,
        icon: 'none'
      });
    }
  }
}
</script>

<script module="sseConnector" lang="renderjs">
export default {
  methods: {
    onSSEIdChange(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        this.startSSE(newVal);
      }
    },
    startSSE(id) {
      // 关闭之前连接
      if (this.source) {
        this.source.close();
      }

      if (!id) {
        this.$ownerInstance.callMethod('handleSSEError', new Error('缺少会话ID'));
        return;
      }
      
      const source = new EventSource(`http://38.207.185.69:3000/ai?id=${encodeURIComponent(id)}`);
      let this_ = this;
      
      source.addEventListener('open', () => {
        console.log('SSE连接已建立');
      });

      source.onmessage = (e) => {
        try {
          const data = JSON.parse(e.data);
          this_.$ownerInstance.callMethod('handleSSEData', data);
        } catch (err) {
          this_.$ownerInstance.callMethod('handleSSEError', err);
        }
      };

      source.onerror = (e) => {
        // 检查是否是连接关闭状态
        if (e.eventPhase === EventSource.CLOSED) {
          this_.$ownerInstance.callMethod('handleSSEError', { 
            type: 'SSE_CLOSED',
            message: 'SSE连接已关闭'
          });
        } else {
          this_.$ownerInstance.callMethod('handleSSEError', e);
        }
        source.close();
      };

      this.source = source;
    }
  }
}
</script>

<style>
.ai-chat-component {
  width: 100%;
  height: 100%;
  background-color: var(--bg-color);
  color: var(--text-color);
}

/* #ifdef H5 */
.ai-chat-component {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
/* #endif */

/* #ifdef APP-PLUS */
.ai-chat-component {
  padding-top: var(--status-bar-height, 0);
}
/* #endif */
</style>